<template>
  <div class="app-container">

    <h2 align="center">发布课程</h2>

    <el-steps :active="active" process-status="wait" finish-status="success" align-center style="margin-bottom: 4px">
      <el-step title="填写课程基本信息"></el-step>
      <el-step title="创建课程大纲"></el-step>
      <el-step title="最终发布"></el-step>
    </el-steps>

    <el-form label-width="120px">
      <el-form-item>

        <el-form-item label="课程标题">
          <el-input v-model="courseInfo.title" placeholder="示例: 机器学习项目课"></el-input>
        </el-form-item>
        <el-form-item label="所属讲师">
          <el-select v-model="courseInfo.teacherId" placeholder="请选择讲师">
            <el-option
              v-for="teacher in teacherList"
              :key="teacher.id"
              :label="teacher.name"
              :value="teacher.id"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="课程分类(级联)">
          <el-cascader
            v-model="cascadeValue"
            :options="subjectList"
            @change="handleChange"></el-cascader>
        </el-form-item>

        <el-form-item label="课程分类">
          <el-select
            v-model="courseInfo.subjectParentId"
            placeholder="请选择课程一级分类"
            @change="onOneSubjectChangeHandler">
            <el-option
              v-for="subject in subjectList"
              :key="subject.id"
              :label="subject.label"
              :value="subject.id"></el-option>
          </el-select>
          <el-select v-model="courseInfo.subjectId" placeholder="请选择课程二级分类">
            <el-option
              v-for="subject in twoSubjectList"
              :key="subject.id"
              :label="subject.label"
              :value="subject.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="总课时">
          <el-input-number :min="0" v-model="courseInfo.lessonNum" controls-position="right"/>
        </el-form-item>
        <el-form-item label="课程简介">
          <Tinymce
            :height="160"
            v-model="courseInfo.description"></Tinymce>
        </el-form-item>

<!--        <el-form-item label="课程封面">
          <PanThumb :image="courseInfo.cover"/>
          <el-button type="primary" icon="el-icon-upload" @click="imageCropperShow=true">设置课程封面</el-button>
          <ImageCropper
            v-show="imageCropperShow"
            :width="300"
            :height="300"
            :key="imageCropperKey"
            :url="BASE_API + '/edu/oss/file/upload'"
            field="file"
            @close="closeUploadBox"
            @crop-upload-success="cropperSuccess" />
        </el-form-item>-->

        <el-form-item label="课程封面">
          <el-upload
            class="avatar-uploader"
            :action="BASE_API + '/oss/file/upload?host=cover'"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="courseInfo.cover" :src="courseInfo.cover" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

        <el-form-item label="课程价格">
          <el-input-number :min="0" v-model="courseInfo.price" controls-position="right"/>
        </el-form-item>

        <el-button-group class="stepActions">
          <!--        <el-button :hidden="true" :disabled="saveBtnDisabled" type="primary" style="margin-top: 12px;" @click="previous">上一步</el-button>-->
          <el-button :disabled="saveBtnDisabled" type="primary" style="margin-top: 12px;" @click="next" class="">保存并下一步</el-button>
        </el-button-group>
      </el-form-item>
    </el-form>

  </div>
</template>

<script>
import courseService from '@/api/edu/course'
import teacherService from '@/api/edu/teacher'
import subjectService from '@/api/edu/subject'

import Tinymce from "@/components/Tinymce"
import PanThumb from "@/components/PanThumb"
import ImageCropper from "@/components/ImageCropper";

export default {
  components: {ImageCropper, Tinymce, PanThumb},
  data() {
    return {
      courseId: '',

      active: 1,
      saveBtnDisabled: false,

      courseInfo: {
        teacherId: '',
        subjectId: '',
        subjectParentId: '',
        title: '',
        lessonNum: 0,
        cover: "/src/test.png",
        price: '',
        description: '',
      },
      rules: {
        teacherId: [
          { required: true }
        ]
      },

      courseInfo1: {
        teacherId: "",
        subjectId: "8888",
        subjectParentId: "8888",
        title: '0302 SpringBoot 高级课程',
        lessonNum: 100,
        price: '2300',
        cover: "https://atguigu-edu-1001.oss-cn-hangzhou.aliyuncs.com/2021/05/05/af8d1e5ed4d949ff98171f28f661d9da-5148ba3065cca49e8d27084da9cd0f96.jpg",
        description: 'springboot 高级',
      },

      // 上传组件参数
      imageCropperShow: false,
      imageCropperKey: 0,
      BASE_API: process.env.VUE_APP_BASE_API,

      teacherList: [],
      subjectList: [],
      twoSubjectList: [],

      cascadeValue: []
    };
  },
  created() {
    this.checkCourseId()

    this.fetchTeacherList()
    this.fetchSubjectList()

    if (this.courseId) {
      this.fetchCourseInfo()
    }
  },
  methods: {
    checkCourseId() {
      if (this.$route.params && this.$route.params.id) {
        this.courseId = this.$route.params.id
      }
    },
    fetchCourseInfo() {
      courseService.getCourseInfo(this.courseId).then(res => {
        this.courseInfo = res.data.data

        // 如果数据库未找到记录,则重定向至添加页面
        if (!this.courseInfo) {
          this.$message({
            type: "error",
            message: "未找到对应课程信息, 请添加课程信息!"
          })
          this.$router.push(`/course/info`)
        }

        this.resolveTwoSubjectList()
      })
    },

    handleChange(value) {
      console.log(value);
    },
    fetchTeacherList() {
      teacherService.getList().then(response => {
        console.log(response)
        this.teacherList = response.data.items
      })
    },
    fetchSubjectList() {
      subjectService.getList().then(response => {
        console.log(response)
        this.subjectList = response.data.items
      })
    },
    resolveTwoSubjectList() {
      this.subjectList.forEach(subject => {
        if (subject.id === this.courseInfo.subjectParentId) {
          this.twoSubjectList = subject.children
          return
        }
      })
    },
    onOneSubjectChangeHandler(value) {
      console.log(value)
      this.courseInfo.subjectId = ''
      this.twoSubjectList = []
      this.subjectList.forEach(subject => {
        if (subject.id === value) {
          this.twoSubjectList = subject.children
          return
        }
      })
      // const result = this.oneSubjectList.filter(subject => subject.id == value)
      // if (result.length == 1) {
      //   this.twoSubjectList = result[0].children
      // }
    },
    next() {
      if (this.courseId) {
        this.updateCourseInfo()
      } else {
        this.addCourseInfo()
      }
    },
    addCourseInfo() {
      courseService.addCourseInfo(this.courseInfo).then(response => {
        console.log(response)

        this.$message({
          type: "success",
          message: "添加课程信息成功"
        })

        // if (this.active++ > 2) this.active = 1;
        this.$router.push(`/course/chapter/${response.data.courseInfo.id}`)
      })
    },
    updateCourseInfo() {
      courseService.updateCourseInfo(this.courseInfo).then(response => {
        console.log(response)

        this.$message({
          type: "success",
          message: "修改课程信息成功"
        })

        // if (this.active++ > 2) this.active = 1;
        this.$router.push(`/course/chapter/${this.courseId}`)
      })
    },

/*    closeUploadBox() {
      this.imageCropperShow = false
      this.imageCropperKey += 1
    },
    cropperSuccess(data) {
      this.courseInfo.cover = data.url
      this.imageCropperShow = false
      this.imageCropperKey += 1
    },*/
    handleAvatarSuccess(res, file) {
      console.log(res)
      console.log(file)
      // this.imageUrl = URL.createObjectURL(file.raw);
      this.courseInfo.cover = res.data.url
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    }
  }
}
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  /*width: 178px;*/
  height: 178px;
  display: block;
}

.tinymce-container {
  line-height: 14px;
}

.el-form-item {
  margin: 3px 0;
  padding: 0px;
}
.stepActions {
  float: right;
  position: relative;
  margin-bottom: 30px;
}
</style>
